/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client;

import compute.Task;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Bartek
 */
public class Primes implements Task<List<Integer>>, Serializable {
    
    
    private int numberOfPrimes;
    
    public Primes(int numberOfPrimes) {
        this.numberOfPrimes = numberOfPrimes;
    }
    
    public List<Integer> execute(ArrayList<Integer> primesBuffer) {
        
        if (this.numberOfPrimes <= primesBuffer.size()) {
            
            ArrayList<Integer> primes = new ArrayList<Integer>();
            
            for (int i = 0; i < numberOfPrimes; i++) {
                primes.add(primesBuffer.get(i));
            }
            
            return primes;
        }
        else {
        
            int bufferSize = primesBuffer.size();
            
            int i = bufferSize;
            
            int j;
            
            if (bufferSize > 0) {
                
                j = primesBuffer.get(primesBuffer.size() - 1) + 1;
            }
            else {
                j = 2;
            }

            while (i < numberOfPrimes) {

                boolean isPrime = true;

                for (int k = 2; k <= Math.sqrt(j); k++) {
                    if (j % k == 0) {
                        isPrime = false;
                        break;
                    }
                }

                if (isPrime) {
                    primesBuffer.add(j);
                    i++;
                }

                j++;
            }

            return primesBuffer;
        }
    }
}
